package com.guanzi.nio.c5;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 管子
 * @date 2025/2/24 21:15
 * @description: MultiThreadServer 类
 */
public class MultiThreadServer {

    private static final Logger log = LoggerFactory.getLogger(MultiThreadServer.class);

    /**
     * Boss线程负责服务端连接建立 ACCEPT事件
     * worker线程负责服务端读取客户端SocketChannel的 READ事件
     */
    public static void main(String[] args) throws IOException {
        Thread.currentThread().setName("boss");
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        Selector boss = Selector.open();
        ssc.register(boss, SelectionKey.OP_ACCEPT, null);
        ssc.bind(new InetSocketAddress(8080));
        log.info("初始化成功......");

        Worker[] workers = new Worker[Runtime.getRuntime().availableProcessors()]; // 当前服务器的核心数（如果在docker会拿到宿主机的核心数，是有坑）
        for (int i = 0; i < workers.length; i++) {
            workers[i] = new Worker("worker-" + i);
        }
        List<Integer> indexList = Arrays.asList(0, 1);
        Random random = new Random();
        while (true) {
            boss.select();
            Iterator<SelectionKey> iter = boss.selectedKeys().iterator();
            while (iter.hasNext()) {
                SelectionKey key = iter.next();
                iter.remove();
                if (key.isAcceptable()) {
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    log.info("connected... {}", sc.getRemoteAddress());

                    // 创建worker线程，并且注册到selector
                    log.info("before register... {}", sc.getRemoteAddress());
                    // 随机分配给两个worker
                    workers[indexList.get(random.nextInt(2)) % workers.length].register(sc);
                    log.info("after register... {}", sc.getRemoteAddress());
                }
            }
        }
    }

    static class Worker implements Runnable {
        private Thread thread;
        private Selector selector;
        private String name;
        // 两个线程间传递数据，且希望控制两个线程的执行顺序，可以使用队列作为消息通道
        private ConcurrentLinkedDeque<Runnable> queue = new ConcurrentLinkedDeque<>();
        private volatile boolean start = false;

        public Worker(String name) {
            this.name = name;
        }

        /**
         * worker的注册方法，每次有新的客户端建立连接时被调用
         * @param sc
         * @throws IOException
         */
        // 初始化线程 和 selector
        public void register(SocketChannel sc) throws IOException {
            if (!start) {
                thread = new Thread(this, name);
                selector = Selector.open();
                thread.start();
                start = true;
            }

            // 向队列添加任务，但没有立刻执行
            queue.add(() -> {
                try {
                    sc.register(selector, SelectionKey.OP_READ, null);
                } catch (ClosedChannelException e) {
                    e.printStackTrace();
                }
            });

            // 主动唤醒selector.select阻塞
            // 第一次调用worker的register方法时，thread.start()方法会因为run方法的selector.select()方法被阻塞。
            // 这里的wakeup是为了保证每次调用时唤醒这个select，从而执行task.run()，将客户端和worker的selector绑定。
            selector.wakeup();
        }

        @Override
        public void run() {
            while (true) {
                try {
                    selector.select();
                    // 从队列取出任务，真正在新线程的run方法里面执行
                    Runnable task = queue.poll();
                    if (null != task) {
                        task.run(); // 执行 sc.register(selector, SelectionKey.OP_READ, null);
                    }

                    Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
                    while (iter.hasNext()) {
                        SelectionKey key = iter.next();
                        iter.remove();
                        if (key.isReadable()) {
                            ByteBuffer buffer = ByteBuffer.allocate(16);
                            SocketChannel channel = (SocketChannel) key.channel();
                            log.info("read... {}", channel.getRemoteAddress());
                            channel.read(buffer);
                            buffer.flip();
                            log.info("读取到消息: {}", Charset.defaultCharset().decode(buffer));
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
